package com.v1.video.util;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.TextUtils;


public class StringUtil {
	private final static char[] hexDigits = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	/**
	 * 处理字符串
	 * 
	 * @param oldStr
	 * @return
	 */
	public static String StrTrim(String oldStr) {
		if (oldStr == null || oldStr.trim().toLowerCase().equals("null"))
			return "";
		else
			return oldStr.trim();
	}

	public static String StrTrim(Object oject) {
		if (oject == null)
			return "";
		else
			return oject.toString().trim();
	}

	public static String StrTrimDate(Object oject) {
		if (oject == null)
			return "";
		else {
			if (oject.toString().length() > 10)
				return oject.toString().trim().substring(0, 10);
			else
				return oject.toString().trim();

		}
	}

	public static String StrTrimTime(Object oject) {
		if (oject == null)
			return "";
		else {
			if (oject.toString().length() > 19)
				return oject.toString().trim().substring(0, 19);
			else
				return oject.toString().trim();

		}
	}

	public static String StrTrimAndTransFromGBToISO(String oldStr) {
		try {
			if (oldStr == null || oldStr.trim().toLowerCase().equals("null"))
				return "";
			else
				return new String(oldStr.trim().getBytes("gb2312"), "ISO8859_1");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";
	}

	public static String StrTrimAndTransFromISOToGB(Object oject) {
		try {
			if (oject == null)
				return "";
			else
				return new String(oject.toString().getBytes("ISO8859_1"),
						"gb2312");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";
	}

	public static String StrTrimAndTransFromGBToISO(Object oject) {
		try {
			if (oject == null)
				return "";
			else
				return new String(oject.toString().getBytes("gb2312"),
						"ISO8859_1");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";
	}

	public static String StrTrimAndTransFromGBToUTF8(Object oject) {
		try {
			if (oject == null)
				return "";
			else
				return new String(oject.toString().getBytes("gb2312"), "utf-8");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";
	}

	/**
	 * MD5-Hex加密
	 * 
	 * @param origin
	 * @return
	 */
	public static String MD5Encode(String origin) {
		String resultString = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(origin.getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultString;
	}

	/**
	 * 转换字节数组为16进制字串
	 * 
	 * @param b
	 *            字节数组
	 * @return 16进制字串
	 */
	public static String byteArrayToHexString(byte bytes[]) {
		// int pos = 0;
		// char[] c = new char[b.length * 2];
		// for (int i = 0; i < b.length; i++) {
		// c[pos++] = hexDigits[(b[i] >> 4) & 0x0F];
		// c[pos++] = hexDigits[b[i] & 0x0f];
		// }
		// return new String(c);

		StringBuffer buf = new StringBuffer(bytes.length * 2);
		int i;

		for (i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buf.toString();

	}

	/**
	 * 转换16进制ASCII字符串为普通字符串
	 * 
	 * @param input
	 *            16进制ASCII字符串
	 * @return 普通字符串
	 */
	public static String formatASCII(String input) {
		String output = "";
		StringBuffer sb = new StringBuffer();
		byte[] bArr = input.getBytes();
		for (int i = 0; i < bArr.length; i++) {
			if (i % 2 == 0) {
				sb.append('%');
			}
			sb.append((char) bArr[i]);
		}
		try {
			output = java.net.URLDecoder.decode(sb.toString(), "GBK");
		} catch (Exception e) {
			return "";
		}
		return output;
	}

	/**
	 * 中文编码转换
	 * 
	 * @param str
	 *            String
	 * @return String
	 */
	public static String toGBK(String str) {
		if (str != null) {
			try {
				str = new String(str.getBytes("ISO-8859-1"), "gb2312");// ！！！
			} catch (Exception e) {
				System.out.println("toGBK Exception:" + e.getMessage());
				System.out.println("The String is:" + str);
			}
		}
		return str;
	}

	/**
	 * 中文编码转换
	 * 
	 * @param str
	 *            原始字符串 charsetName 字符集名称，如"ISO" String
	 * @return String
	 */
	public static String toGBK(String str, String charsetName) {
		if (str != null && charsetName != null) {
			try {
				str = new String(str.getBytes(charsetName), "gb2312");// ！！！
			} catch (Exception e) {
				System.out.println("toGBK Exception:" + e.getMessage());
				System.out.println("The String is:" + str);
			}
		}
		return str;
	}

	public static void testStringCharset(String str) {
		try {
			System.out.println("[ISO8859-1]:  "
					+ new String(str.getBytes("ISO8859-1"), "gb2312"));
			System.out.println("[ISO-8859-1]:  "
					+ new String(str.getBytes("ISO-8859-1"), "gb2312"));
			System.out.println("[UTF8]:  "
					+ new String(str.getBytes("UTF8"), "gb2312"));
			System.out.println("[UTF-8]:  "
					+ new String(str.getBytes("UTF-8"), "gb2312"));
			System.out.println("[GB2312]:  "
					+ new String(str.getBytes("GB2312"), "gb2312"));
			System.out.println("[GBK]:  "
					+ new String(str.getBytes("GBK"), "gb2312"));
			System.out.println("[BIG5]:  "
					+ new String(str.getBytes("BIG5"), "gb2312"));
			System.out.println("[UNICODE]:  "
					+ new String(str.getBytes("UNICODE"), "gb2312"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public static String cutString(String str, int length) {
		if ((length > 0) && (str.length() > length)) {
			return str.substring(0, length) + ".";
		} else
			return str;
	}

	// 获得文件后缀名:
	public static String getFileType(String fileName) {
		String result = "file";
		if (fileName.contains(".")) {
			result = fileName.substring(fileName.lastIndexOf(".") + 1);
		}
		return result;
	}

	/**
	 * 将普通文本格式字符串装换为html字符串
	 * 
	 * @param in
	 * @return
	 */
	public static String toHTMLString(String in) {
		StringBuffer out = new StringBuffer();
		for (int i = 0; in != null && i < in.length(); i++) {
			char c = in.charAt(i);
			if (c == '\'')
				out.append("&#039;");
			else if (c == '\"')
				out.append("&#034;");
			else if (c == '<')
				out.append("&lt;");
			else if (c == '>')
				out.append("&gt;");
			else if (c == '&')
				out.append("&amp;");
			else if (c == ' ')
				out.append("&nbsp;");
			else if (c == '\n')
				out.append("<br/>");
			else
				out.append(c);
		}
		return out.toString();
	}

	/**
	 * 去除html字符串的格式
	 * 
	 * @param htmlstr
	 * @return
	 */
	public static String toTxtString(String htmlstr) {
		String result = StrTrim(htmlstr);
		// 去除html格式
		result = result.replaceAll("<([^<>]+)>", "").replace("&nbsp;", "");
		return result;
	}

	// 转为unicode
	public static void writeUnicode(final DataOutputStream out,
			final String value) {
		try {
			final String unicode = codeUnicode(value);
			final byte[] data = unicode.getBytes();
			final int dataLength = data.length;

			System.out.println("Data Length is: " + dataLength);
			System.out.println("Data is: " + value);
			out.writeInt(dataLength); // 先写出字符串的长度
			out.write(data, 0, dataLength); // 然后写出转化后的字符串
		} catch (IOException e) {

		}
	}

	/**
	 * 将普通字符串转为unicode编码，如输入【测试】，返回【&#x6d4b;&#x8bd5;】
	 * 
	 * @param dataStr
	 * @return 转换后的字符串
	 */
	public static String codeUnicode(final String dataStr) {
		char[] utfBytes = dataStr.toCharArray();
		String unicodeBytes = "";
		for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
			String hexB = Integer.toHexString(utfBytes[byteIndex]);
			if (hexB.length() <= 2) {
				hexB = "00" + hexB;
			}
			unicodeBytes = unicodeBytes + "&#x" + hexB + ";";
		}
		return unicodeBytes;
	}

	/**
	 * 用于测试codeUnicode函数
	 * 
	 * @param gbString
	 */
	private static void gbEncoding(final String gbString) {
		System.out.println(gbString + "unicodeBytes is: ");
		System.out.println(codeUnicode(gbString));
	}

	/**
	 * 
	 * 转换字符串为int型值
	 * 
	 * @param str
	 *            待转换的字符串
	 * @param defvalue
	 *            转换失败时的默认返回值
	 * @return
	 */
	public static int parseStrToInt(String str, int defvalue) {
		try {
			int result = new Integer(StrTrim(str)).intValue();
			return result;
		} catch (Exception e) {
			return defvalue;
		}
	}

	/**
	 * 
	 * 转换字符串为Long型值
	 * 
	 * @param str
	 *            待转换的字符串
	 * @param defvalue
	 *            转换失败时的默认返回值
	 * @return
	 */
	public static Long parseStrToLong(String str, int defvalue) {
		try {
			Long result = new Long(StrTrim(str));
			return result;
		} catch (Exception e) {
			return new Long(defvalue);
		}
	}

	public static Double parseStrToDouble(String str, double defvalue) {
		try {
			Double result = new Double(str);
			return result;
		} catch (Exception e) {
			return new Double(defvalue);
		}
	}

	public static double getdoubleValue(String str, double defvalue) {
		return parseStrToDouble(str, defvalue).doubleValue();
	}

	/**
	 * 功能介绍:将unicode字符串转为汉字，如输入【&#x6d4b;&#x8bd5;】，返回【测试】
	 * 
	 * @param dataStr
	 *            源unicode字符串
	 * @return 转换后的字符串
	 */
	public static String decodeUnicode(final String dataStr) {
		int start = 0;
		int end = 0;
		final StringBuffer buffer = new StringBuffer();
		while (start > -1) {
			end = dataStr.indexOf("&#x", start + 2);
			String charStr = "";
			if (end == -1) {
				charStr = dataStr.substring(start + 3, dataStr.length() - 1);
			} else {
				charStr = dataStr.substring(start + 3, end - 1);
			}
			char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
			buffer.append(new Character(letter).toString());
			start = end;
		}
		return buffer.toString();
	}

	public static final String encodeHex(byte[] bytes) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		int i;

		for (i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buf.toString();
	}

	public static void printCode(String[] strArr, String codeTmpl) {
		if (strArr != null && strArr.length > 0 && codeTmpl != null) {
			for (int i = 0; i < strArr.length; i++) {
				System.out.println(codeTmpl.replaceAll("@var", strArr[i]));
			}
		}
	}

	/**
	 * 取得字符串中的数字，按顺序组合成字符串
	 * 
	 * @return
	 */
	public static String getNumberStr(String s) {
		String result = "";
		s = s.trim();
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) >= '0' && s.charAt(i) <= '9')
				result = result + s.charAt(i);
		}
		return result;
	}

	public static String getSql(String hscodes) {
		String result = "";
		if (hscodes != null && !"".equals(hscodes)) {
			String[] hsArray = hscodes.split(";");
			for (int i = 0; i < hsArray.length; i++) {
				result += " or hs='" + hsArray[i] + "' ";
			}
		}
		return result;
	}

	/**
	 * 把字符串转为逗号分隔的字符串 如：输入： AFBD 输出：
	 * 
	 * @param source
	 * @return
	 */
	public static String getCommaStr(String source) {
		String result = "";
		char[] arrChar = StrTrim(source).toCharArray();

		for (int i = 0; i < arrChar.length; i++) {
			result += "'" + arrChar[i] + "',";
		}

		if (result.endsWith(",")) {
			result = result.substring(0, result.length() - 1);
		}
		return result;
	}

	public static boolean isEmail(String strEmail) {
		String strPattern = "^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";

		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(strEmail);
		return m.matches();
	}
	

	/**
	 * 判断字符串是否是数字
	 */
	public static boolean isNumeric(String str) {
		if(str==null)
			return false;
		
		Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	} 
	
	/**
	 * 
	 * @param sizeStr
	 * @return
	 */
	public static String readableFileSize(String sizeStr) {
		try {
			if (TextUtils.isEmpty(sizeStr) || !TextUtils.isDigitsOnly(sizeStr))
				return sizeStr;
			long size = Long.parseLong(sizeStr);
			if (size <= 0)
				return "0";
			final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
			int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
			return new DecimalFormat("#,##0.#").format(size
					/ Math.pow(1024, digitGroups))
					+ " " + units[digitGroups];
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "";
	}
	
	/*
	 * Java文件操作 获取文件扩展名 如：aaa.txt  返回 txt
	 */
	public static String getFileExtName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	/*
	 * Java文件操作 获取不带扩展名的文件名
	 */
	public static String getFileNameNoExt(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length()))) {
				return filename.substring(0, dot);
			}
		}
		return filename;
	} 
        
	public static void main(String arg[]) {
		
//		System.out.println(isNumeric(null));
//		System.out.println(isNumeric("85a"));
//		System.out.println(isNumeric("12.3"));
//		System.out.println(isNumeric("-12.3"));
//		System.out.println(isNumeric("85aa"));
//		System.out.println(isNumeric("12.3%"));
//		
//		System.out.println("dd".substring(0,8));
/*		String[] ary = "1,2".split(",");
		String inStr = "''"; 
		for (int i = 0; i < ary.length; i++) {
			inStr += ", '" + ary[i]+"'";
		}
		System.out.println("in ("+inStr+")");
*/
//		String test = "[page]<div style=\"text-align: center\"><strong>Announcement No. 92, 2010 of the General Administration of Customs of the P. R. China (GACC)</strong></div><br/>";
//		System.out.println(toTxtString(test).replaceAll("\\[page\\]", ""));
//		System.out.println(getLimitString("select * from custom_info", DBType.ORACLE, 10, 20));
//		System.out.println(getLimitString("select * from sys_supervision order by id", DBType.MYSQL, 10, 20));
		System.out.println(getFileExtName("http://lllsdlajf.asdkfjlddd.mp4"));
	}

}
